package cn.nfwx.tv.fragment.me;

import android.app.Activity;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.nfwx.tv.R;
import cn.nfwx.tv.activity.CcpActivity;
import cn.nfwx.tv.activity.SpalshActivity;
import cn.nfwx.tv.base.BaseDialogFragment;
import cn.nfwx.tv.controller.me.MineLeftController;
import cn.nfwx.tv.events.BindToLoginEvents;
import cn.nfwx.tv.events.ToForgetPWEvents;
import cn.nfwx.tv.events.ToLoginEvents;
import cn.nfwx.tv.events.ToMineItemEvent;
import cn.nfwx.tv.events.ToSmsLoginEvents;
import cn.nfwx.tv.events.WxBindPhoneEvents;
//import cn.nfwx.tv.fragment.BindPhoneFragment;
import cn.nfwx.tv.fragment.NullFragment;
import cn.nfwx.tv.fragment.SettingFragment;
import cn.nfwx.tv.fragment.ShareFragment;
import cn.nfwx.tv.fragment.callback.ActionCallback;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.model.User;
import cn.nfwx.tv.okhttp.CustomOkHttpClient;
import cn.nfwx.tv.service.DownloadService;
import cn.nfwx.tv.util.LogUtil;
import cn.nfwx.tv.util.ToastUtil;

public class MineFragment extends BaseDialogFragment implements MineLeftController.OnMineClickListener, LifecycleObserver {

    public static final int POSITION_LOGIN = 0;
    public static final int POSITION_REGISTER = 1;
    public static final int POSITION_SUBSCRIPT = 2;
    public static final int POSITION_APPOINT = 3;
    public static final int POSITION_HISTORY = 4;
    public static final int POSITION_DOWNLOAD = 5;
    public static final int POSITION_SETTING = 6;
    public static final int POSITION_SHARE = 7;
    public static final int POSITION_BINDPHONE = 8;
    public static final int POSITION_SMS = 9;
    public static final int POSITION_FORGETPWD = 10;
    public static final int POSITION_ABOUT = 11;

    private static final String KEY_POSITION = "KEY_POSITION";

    private MineLeftController mineLeftController;
    private boolean isBind;
    private int currentPosition = -1;

    private Fragment nowFragment;
    private NullFragment nullFragment;
//    private MineAllFragment historyFragment;
//    private ForgetPasswdFragment forgetPasswdFragment;
//    private SmsLoginFragment smsLoginFragment;

    public boolean isBackEvent = true;
    private ActionCallback mActionCallback;
    public final static String ACTION_MINE_DIMISS = "ACTION_MINE_DIMISS";

    /**
     * 是否填满整个屏幕
     */
    protected boolean isMatchParent() {
        return true;
    }

    protected boolean isOutsideTouchable() {
        return true;
    }

    //是否透明背景
    protected boolean isTranslucentBackground() {
        return false;
    }

    protected boolean isTranslucentStatus() {
        return false;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
    }

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }

    public static MineFragment newInstance(int position) {
        MineFragment fragment = new MineFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_POSITION, position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActionCallback = ActionCallback.NONE;
        if (activity instanceof ActionCallback) {
            mActionCallback = (ActionCallback) activity;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mActionCallback = ActionCallback.NONE;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mineLeftController = new MineLeftController(getActivity(), findView(R.id.rl_mine_left));
        initListen();
        loadData();
    }


    private void initListen() {
        mineLeftController.setOnMineClickListener(this);
    }

    private void loadData() {
        int index;
        if (AccountHelper.getInstance().isLogin(getContext())) {
            if (getArguments() != null) {
                index = getArguments().getInt(KEY_POSITION, POSITION_SUBSCRIPT);
            } else {
                index = POSITION_SUBSCRIPT;
            }
        } else {
            index = POSITION_LOGIN;
        }
        nowFragment = NullFragment.newInstance(index);
        showFragment(index);
    }

    public void loadResultData(int position) {
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_POSITION, position);
        this.setArguments(bundle);
    }

    private void showFragment(int index) {
        if (currentPosition == index) {
            return;
        }
        if (index == POSITION_SUBSCRIPT || index == POSITION_APPOINT
                || index == POSITION_HISTORY || index == POSITION_DOWNLOAD
                || index == POSITION_SETTING) {
            if (isBind) {
                showBindPhoneNotice(index);
                return;
            }
        }
        currentPosition = index;
        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (AccountHelper.getInstance().isLogin(getContext())) {
            mineLeftController.showItem(index);
            switch (index) {
                case POSITION_SUBSCRIPT:
                    //if (subscriptFragment == null) {
                    MineAllFragment subscriptFragment = MineAllFragment.newInstance(POSITION_SUBSCRIPT);
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, subscriptFragment);
                    nowFragment = subscriptFragment;
//                    } else {
//                        if (nowFragment != subscriptFragment) {
//                            fragmentTransaction.hide(nowFragment).replace(R.id.container, subscriptFragment);
//                            fragmentTransaction.show(subscriptFragment);
//                            nowFragment = subscriptFragment;
//                        }
//                    }
                    break;
                case POSITION_APPOINT:
                    MineAllFragment appointmentFragment = MineAllFragment.newInstance(POSITION_APPOINT);
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, appointmentFragment);
                    nowFragment = appointmentFragment;
                    break;
                case POSITION_HISTORY:
                    MineAllFragment historyFragment = MineAllFragment.newInstance(POSITION_HISTORY);
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, historyFragment);
                    nowFragment = historyFragment;
                    break;
                case POSITION_DOWNLOAD:
                    MineAllFragment myDownLoadFragment = MineAllFragment.newInstance(POSITION_DOWNLOAD);
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, myDownLoadFragment);
                    nowFragment = myDownLoadFragment;
                    break;
                case POSITION_ABOUT:
                    mineLeftController.showItem(POSITION_ABOUT);
                    AboutFragment aboutFragment = new AboutFragment();
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, aboutFragment);
                    nowFragment = aboutFragment;
                    break;
                case POSITION_SETTING:
                    mineLeftController.showItem(-1);
                    SettingFragment settingFragment = new SettingFragment();
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, settingFragment);
                    nowFragment = settingFragment;
                    break;
                case POSITION_SHARE:
                    mineLeftController.showItem(POSITION_SHARE);
                    ShareFragment shareFragment = ShareFragment.newInstance();
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, shareFragment);
                    nowFragment = shareFragment;
                    break;
                case POSITION_BINDPHONE:
                    //if (bindPhoneFragment == null) {
//                    BindPhoneFragment bindPhoneFragment = BindPhoneFragment.newInstance(wxid);
//                    fragmentTransaction.hide(nowFragment).replace(R.id.container, bindPhoneFragment);
//                    nowFragment = bindPhoneFragment;
                    break;
            }
        } else {
            mineLeftController.showItem(-1);
            switch (index) {
                case POSITION_LOGIN:
                case POSITION_REGISTER:
                    MineLoginFragment loginFragment = MineLoginFragment.newInstance();
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, loginFragment);
                    nowFragment = loginFragment;
                    break;
                case POSITION_ABOUT:
                    mineLeftController.showItem(POSITION_ABOUT);
                    AboutFragment aboutFragment = new AboutFragment();
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, aboutFragment);
                    nowFragment = aboutFragment;
                    break;
                case POSITION_SETTING:
                    mineLeftController.showItem(POSITION_SETTING);
                    SettingFragment settingFragment = new SettingFragment();
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, settingFragment);
                    nowFragment = settingFragment;
                    break;
                case POSITION_SHARE:
                    mineLeftController.showItem(POSITION_SHARE);
                    ShareFragment shareFragment = ShareFragment.newInstance();
                    fragmentTransaction.hide(nowFragment).replace(R.id.container, shareFragment);
                    nowFragment = shareFragment;
                    break;
                case POSITION_BINDPHONE:
                    //if (bindPhoneFragment == null) {
//                    BindPhoneFragment bindPhoneFragment = BindPhoneFragment.newInstance(wxid);
//                    fragmentTransaction.hide(nowFragment).replace(R.id.container, bindPhoneFragment);
//                    nowFragment = bindPhoneFragment;
                    break;
                case POSITION_SMS:
//                    smsLoginFragment = new SmsLoginFragment();
//                    fragmentTransaction.hide(nowFragment).replace(R.id.container, smsLoginFragment);
//                    nowFragment = smsLoginFragment;
                    break;
                case POSITION_FORGETPWD:
//                    forgetPasswdFragment = new ForgetPasswdFragment();
//                    fragmentTransaction.hide(nowFragment).replace(R.id.container, forgetPasswdFragment);
//                    nowFragment = forgetPasswdFragment;
                    break;
                default:
                    mineLeftController.showItem(index);
                    nullFragment = NullFragment.newInstance(index);
                    fragmentTransaction.hide(nowFragment).add(R.id.container, nullFragment);
                    nowFragment = nullFragment;
                    break;
            }
        }
        fragmentTransaction.commit();
    }

    @Override
    public void close() {
        if (isBind) {
            showBindPhoneNotice(POSITION_SUBSCRIPT);
            return;
        }
        dismiss();
    }

    @Override
    public void login() {
        isBind = false;
        showFragment(POSITION_LOGIN);
    }

    @Override
    public void register() {
        isBind = false;
        showFragment(POSITION_REGISTER);
    }

    @Override
    public void zixun() {
        CcpActivity.startActivity(getContext());
    }

    @Override
    public void subscript() {
        showFragment(POSITION_SUBSCRIPT);
    }

    @Override
    public void appoint() {
        showFragment(POSITION_APPOINT);
    }

    @Override
    public void history() {
        showFragment(POSITION_HISTORY);
    }

    @Override
    public void download() {
        showFragment(POSITION_DOWNLOAD);
    }

    @Override
    public void about() {
        showFragment(POSITION_ABOUT);
    }

    @Override
    public void setting() {
        showFragment(POSITION_SETTING);
    }

    @Override
    public void logout() {
        if (isBind) {
            showBindPhoneNotice(POSITION_SUBSCRIPT);
            return;
        }

        if (AccountHelper.getInstance().isLogin(getContext())) {
            DialogFragmentHelper.showConfirmDialog(getChildFragmentManager(), null, "确定要退出吗？", "取消", "确定", true, null, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isBind = false;
                    AccountHelper.getInstance().clearUser(getContext());
                    //SharePrefUtil.clearWechatUser(getContext());
                    //mineLeftController.refreshLoginStats();
                    //showFragment(POSITION_LOGIN);
                    SpalshActivity.startActivity(getContext(), SpalshActivity.KEY_LOGIN);
                    getActivity().finish();
                }
            });
        } else {
            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void share() {
        showFragment(POSITION_SHARE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toLoginEventBus(ToLoginEvents events) {
        isBind = false;
        //wecahtUser=null;
        int loginCurrentPosition = events.getPosition();
        if (loginCurrentPosition == 0) {
            showFragment(POSITION_LOGIN);
        } else if (loginCurrentPosition == 1) {
            showFragment(POSITION_REGISTER);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toSmsLoginEventBus(ToSmsLoginEvents events) {
        isBind = false;
        showFragment(POSITION_SMS);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toForgetPWEventBus(ToForgetPWEvents events) {
        isBind = false;
        showFragment(POSITION_FORGETPWD);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toBindPhoneEventBus(final WxBindPhoneEvents events) {
        if (getChildFragmentManager().isStateSaved()) {
            ThreadHelper.postDelayed(new Runnable() {
                @Override
                public void run() {
                    EventBus.getDefault().post(events);
                }
            }, 500);
        } else {
            User wxUser = events.getWxUser();
            if (wxUser.getUid() == 0) {
                isBind = true;
                showFragment(POSITION_BINDPHONE);
            } else {
                isBind = false;
                AccountHelper.getInstance().saveUser(getActivity(), wxUser);
                if (mineLeftController != null) {
                    mineLeftController.refreshLoginStats();
                }
                showFragment(POSITION_SUBSCRIPT);
                ToastUtil.show(getActivity(), "登录成功");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toBindToLoginEventBus(BindToLoginEvents events) {
        isBind = false;
        //wecahtUser = null;
        //loginCurrentPosition = events.getPosition();
        showFragment(POSITION_LOGIN);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toMineItemEventBus(ToMineItemEvent event) {
        if (event.isBindSuccess()) {
            isBind = false;
        }
        if (mineLeftController != null) {
            mineLeftController.refreshLoginStats();
        }
        showFragment(event.getPosition());
    }

    private void showBindPhoneNotice(final int index) {
        DialogFragmentHelper.showConfirmDialog(getChildFragmentManager(), "加油~只差一步就登录成功了", "确定要放弃吗", "不放弃", "放弃登录", true, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isBind = true;
                DialogFragmentHelper.closeConfirmDialog(getChildFragmentManager());
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isBind = false;
                DialogFragmentHelper.closeConfirmDialog(getChildFragmentManager());
                showFragment(index);
            }
        });
    }

    @Override
    public void dismiss() {
        super.dismiss();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void release() {
        if (mActionCallback != ActionCallback.NONE) {
            if (isBackEvent) {
                if (AccountHelper.getInstance().isLogin(getContext()) && getActivity() != null && !getActivity().isFinishing()) {
                    mActionCallback.callbackByfragment(ACTION_MINE_DIMISS, null);
                }
            } else {
                isBackEvent = true;
            }
        }
        nowFragment = null;
        if (mineLeftController != null) {
            mineLeftController.release();
        }
        EventBus.getDefault().unregister(this);
    }
}
